#include "camera.h"
#include <QDebug>
Camera::Camera() :_pos(0, 0) , _scale(1), _rotation(0), _window(0, 0), _background(10000, 10000){}

void Camera::updateBackgroundSize(const QSize &size)
{
    _background = size;
    qDebug() << "相机背景 : " << _background;
    update(_pos, _scale, _rotation, _window);
}

void Camera::updateWindowSize(const QSize &window)
{
    update(_pos, _scale, _rotation, window);
}

void Camera::updatePosition(const QPointF &pos)
{
    update(_pos + pos, _scale, _rotation, _window);
}

void Camera::updateScale(float scale)
{
    update(_pos, scale, _rotation, _window);
}

void Camera::updateRotation(float rotation)
{
    update(_pos, _scale, rotation, _window);
}

void Camera::update(const QPointF &pos, float scale, float rotation, const QSize &window)
{
    _window = window;

    if(scale) {
        // 不能让窗口大小,大于图片的大小：
        float min_scale_x = (float)_window.width() / _background.width();
        float min_scale_y = (float)_window.height() / _background.height();
        float min_scale = qMax(min_scale_x, min_scale_y);

        scale = qMax(scale, min_scale);  // 确保不会小于最小缩放值
        scale = qMin(scale, 2.0f);
        _scale = scale;
    } else {
        _scale = 1;
    }

    double min_width = _window.width() / (2.0 * _scale);
    double min_height = _window.height() / (2.0 * _scale);
    double max_width = _background.width() - min_width;
    double max_height = _background.height() - min_height;

    if(pos.x() < min_width){
        _pos.setX(min_width);
    } else if(pos.x() > max_width){
        _pos.setX(max_width);
    } else {
        _pos.setX(pos.x());
    }

    if(pos.y() < min_height){
        _pos.setY(min_height);
    } else if (pos.y() > max_height){
        _pos.setY(max_height);
    } else {
        _pos.setY(pos.y());
    }

    _rotation = rotation;

    qDebug() << "相机信息更改为:" << _pos << _scale << _rotation << _window;
}

void Camera::setCamera(QPainter &painter)
{
    painter.translate(_window.width() / 2, _window.height() / 2); // 移动到屏幕中心
    painter.scale(_scale, _scale); // 应用缩放
    painter.rotate(_rotation); // 应用旋转
    painter.translate(-_pos.x(), -_pos.y()); // 应用摄像机位置偏移（注意是负值）
}

void Camera::toCenter()
{
    _pos = QPointF(_background.width() / 2, _background.height() / 2);
    _scale = 1;
    _rotation = 0;
}

QPointF Camera::windowToGlobal(const QPointF &windowPos) const
{
    QTransform transform;
    transform.translate(_pos.x(), _pos.y());
    transform.rotate(_rotation);
    transform.scale(1 / _scale, 1 / _scale);
    transform.translate(-_window.width() / 2, -_window.height() / 2);

    return transform.map(windowPos);
}

QPointF Camera::globalToWindow(const QPointF &globalPos) const
{
    QTransform transform;
    transform.translate(_window.width() / 2, _window.height() / 2);
    transform.scale(_scale, _scale);
    transform.rotate(-_rotation);
    transform.translate(-_pos.x(), -_pos.y());

    return transform.map(globalPos);
}
